<template>
	<xn-form-container
		:title="formData.id ? '编辑面试安排' : '新增面试安排'"
		:width="600"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="候选人姓名" name="candidateName">
						<a-input v-model:value="displayData.candidateName" placeholder="请输入候选人姓名" disabled />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="推荐城市" name="city">
						<a-input v-model:value="displayData.cityName" placeholder="推荐城市" disabled />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="推荐职位" name="recommendedPositionCode">
						<a-input v-model:value="displayData.recommendedPositionName" placeholder="推荐职位" disabled />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="推荐部门" name="recommendedDepartment">
						<a-input v-model:value="displayData.recommendedDepartmentName" placeholder="推荐部门" disabled />
					</a-form-item>
				</a-col>
			</a-row>

			<!-- 面试预约部分 -->
			<template v-if="showSection === 'scheduling'">
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item label="面试时间" name="interviewTime">
							<a-date-picker
								v-model:value="interviewTimeValue"
								show-time
								format="YYYY-MM-DD HH:mm"
								placeholder="请选择面试时间"
								style="width: 100%"
								:disabled-date="disabledDate"
							/>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="面试方式" name="interviewMethod">
							<a-select
								v-model:value="formData.interviewMethod"
								placeholder="请选择面试方式"
								:options="interviewMethodOptions"
								:allowClear="true"
							/>
						</a-form-item>
					</a-col>
				</a-row>

				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item label="面试官" name="interviewer">
							<a-input
								@click="interviewerSelectorRef.showUserPlusModal()"
								:value="interviewerUser.name ? interviewerUser.name : ''"
								placeholder="请选择面试官"
								readonly
							/>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="核心面试官" name="coreInterviewer">
							<a-input
								@click="coreInterviewerSelectorRef.showUserPlusModal()"
								:value="coreInterviewerUser.name ? coreInterviewerUser.name : ''"
								placeholder="请选择核心面试官"
								readonly
							/>
						</a-form-item>
					</a-col>
				</a-row>
			</template>

			<!-- 面试结果部分 -->
			<template v-if="showSection === 'result'">
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item label="面试结果" name="interviewResult">
							<a-select
								v-model:value="formData.interviewResult"
								placeholder="请选择面试结果"
								:options="interviewResultOptions"
								:allowClear="true"
							/>
						</a-form-item>
					</a-col>
				</a-row>
				<a-form-item label="面试反馈意见" name="interviewFeedback">
					<a-textarea v-model:value="formData.interviewFeedback" placeholder="请输入面试反馈意见" :rows="4" />
				</a-form-item>
			</template>

			<!-- 录用跟进部分 -->
			<template v-if="showSection === 'followup'">
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item label="录用跟进" name="hiringResult">
							<a-select
								v-model:value="formData.hiringResult"
								placeholder="请选择录用跟进状态"
								:options="hiringResultOptions"
								:allowClear="true"
								@change="onhiringResultChange"
							/>
						</a-form-item>
					</a-col>
					<a-col :span="12" v-if="formData.hiringResult === 'AGREE'">
						<a-form-item label="入职日期" name="onboardingDate" :rules="onboardingDateRules">
							<a-date-picker
								v-model:value="onboardingDateValue"
								format="YYYY-MM-DD"
								placeholder="请选择入职日期"
								style="width: 100%"
								:disabled-date="disabledDate"
							/>
						</a-form-item>
					</a-col>
				</a-row>

				<!-- 发送Offer选项 -->
				<template v-if="formData.hiringResult === 'AGREE'">
					<a-row :gutter="24">
						<a-col :span="12">
							<a-form-item label="发送Offer" name="sendOffer">
								<div style="display: flex; align-items: center">
									<a-switch v-model:checked="formData.sendOffer" />
									<a-tooltip title="通过邮箱发送offer，同时附带二维码，供候选人自助填写入职信息">
										<question-circle-outlined style="margin-left: 8px; color: #1890ff" />
									</a-tooltip>
								</div>
							</a-form-item>
						</a-col>
					</a-row>

					<!-- Offer表单组件 -->
					<template v-if="formData.sendOffer">
						<OfferForm v-model="formData.offerEntity" :send-offer="formData.sendOffer" ref="offerFormRef" />
					</template>
				</template>

				<a-form-item label="录用备注" name="remark">
					<a-textarea v-model:value="formData.remark" placeholder="录用备注" :rows="4" />
				</a-form-item>
			</template>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
		<!-- 面试官选择器 -->
		<UserSelectorPlus
			ref="interviewerSelectorRef"
			data-type="object"
			:user-show="false"
			:radio-model="true"
			@onBack="interviewerCallBack"
		/>
		<!-- 核心面试官选择器 -->
		<UserSelectorPlus
			ref="coreInterviewerSelectorRef"
			data-type="object"
			:user-show="false"
			:radio-model="true"
			@onBack="coreInterviewerCallBack"
		/>
	</xn-form-container>
</template>

<script setup>
	import { required } from '@/utils/formRules'
	import recruitmentProfileApi from '@/api/hrms/recruitment/profile/recruitmentProfileApi'
	import { message } from 'ant-design-vue'
	import { reactive, ref, watch } from 'vue'
	import UserSelectorPlus from '@/components/Selector/userSelectorPlus.vue'
	import dayjs from 'dayjs'
	import { QuestionCircleOutlined } from '@ant-design/icons-vue'
	import tool from '@/utils/tool'
	import OfferForm from './offer.vue'

	// 基础引用和状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const interviewerSelectorRef = ref()
	const coreInterviewerSelectorRef = ref()
	const submitLoading = ref(false)
	const interviewTimeValue = ref(null)
	const onboardingDateValue = ref(null)
	const offerFormRef = ref()

	// 字典选项
	const interviewMethodOptions = tool.dictList('INTERVIEW_METHOD')
	const interviewResultOptions = tool.dictList('INTERVIEW_RESULT')
	const hiringResultOptions = tool.dictList('HIRING_RESULT')

	// 入职日期校验规则
	const onboardingDateRules = ref([])

	// 要展示的部分
	const showSection = ref('')

	// 展示数据
	const displayData = reactive({
		candidateName: undefined,
		city: undefined,
		cityName: undefined,
		recommendedPositionCode: undefined,
		recommendedPositionName: undefined,
		recommendedDepartmentId: undefined,
		recommendedDepartmentName: undefined
	})

	// 表单数据
	const formData = reactive({
		id: undefined,
		interviewTime: undefined,
		interviewMethod: undefined,
		interviewer: undefined,
		coreInterviewer: undefined,
		interviewResult: undefined,
		interviewFeedback: undefined,
		hiringResult: undefined,
		onboardingDate: undefined,
		sendOffer: false,
		offerEntity: {
			positionName: undefined,
			offerEmail: undefined,
			probationPeriod: undefined,
			preTaxSalary: undefined,
			discountRate: undefined,
			probationSalary: undefined,
			workLocation: undefined,
			position: undefined,
			companyContact: undefined,
			contactPhone: undefined
		},
		remark: undefined
	})

	// 面试官信息
	const interviewerUser = reactive({
		id: undefined,
		name: ''
	})

	// 核心面试官信息
	const coreInterviewerUser = reactive({
		id: undefined,
		name: ''
	})

	// 表单验证规则
	const formRules = {
		interviewTime: [required('请选择面试时间')],
		interviewMethod: [required('请选择面试方式')],
		interviewer: [required('请选择面试官')],
		coreInterviewer: [required('请选择核心面试官')],
		interviewResult: [required('请选择面试结果')],
		interviewFeedback: [required('请输入面试反馈意见')],
		hiringResult: [required('请选择录用跟进状态')]
	}

	// 禁用日期函数
	const disabledDate = (current) => {
		return current && current < dayjs().startOf('day')
	}

	// 监听面试时间变化
	watch(interviewTimeValue, (newVal) => {
		formData.interviewTime = newVal?.format('YYYY-MM-DD HH:mm') || undefined
	})

	// 监听入职日期变化
	watch(onboardingDateValue, (newVal) => {
		formData.onboardingDate = newVal?.format('YYYY-MM-DD') || undefined
	})

	// 监听发送Offer开关变化
	watch(
		() => formData.sendOffer,
		(newVal) => {
			if (!newVal) {
				Object.keys(formData.offerEntity).forEach((key) => {
					formData.offerEntity[key] = undefined
				})
			}
		}
	)

	// 录用跟进变化处理
	const onhiringResultChange = (value) => {
		// 清空入职日期
		formData.onboardingDate = undefined
		onboardingDateValue.value = null

		if (value === 'AGREE') {
			onboardingDateRules.value = [required('请选择入职日期')]
		} else {
			onboardingDateRules.value = []
			formData.sendOffer = false
			Object.keys(formData.offerEntity).forEach((key) => {
				formData.offerEntity[key] = undefined
			})
		}
	}

	// 打开抽屉
	const onOpen = (record, section) => {
		visible.value = true
		showSection.value = section
		if (!record) return
		formData.id = record.id
		displayData.candidateName = record.candidateName
		displayData.city = record.city || ''
		displayData.cityName = record.cityName || ''
		displayData.recommendedPositionCode = record.recommendedPositionCode || ''
		displayData.recommendedPositionName = record.recommendedPositionCodeName || ''
		displayData.recommendedDepartmentId = record.recommendedDepartment || ''
		displayData.recommendedDepartmentName = record.recommendedDepartmentName || ''
		formData.offerEntity.positionName = record.recommendedPositionCodeName
		switch (section) {
			case 'scheduling':
				// 面试预约部分
				formData.interviewTime = record.interviewTime
				formData.interviewMethod = record.interviewMethod
				formData.interviewer = record.interviewer
				formData.coreInterviewer = record.coreInterviewer
				if (record.interviewTime) {
					interviewTimeValue.value = dayjs(record.interviewTime, 'YYYY-MM-DD HH:mm')
				}
				if (record.interviewer && record.interviewerName) {
					interviewerUser.id = record.interviewer
					interviewerUser.name = record.interviewerName
				}
				if (record.coreInterviewer && record.coreInterviewerName) {
					coreInterviewerUser.id = record.coreInterviewer
					coreInterviewerUser.name = record.coreInterviewerName
				}
				break
			case 'result':
				formData.interviewResult = record.interviewResult
				formData.interviewFeedback = record.interviewFeedback
				break
			case 'followup':
				formData.hiringResult = record.hiringResult
				formData.onboardingDate = record.onboardingDate
				formData.sendOffer = record.sendOffer || false
				formData.remark = record.remark || undefined
				if (record.onboardingDate) {
					onboardingDateValue.value = dayjs(record.onboardingDate, 'YYYY-MM-DD')
				}
				if (formData.hiringResult === 'AGREE') {
					onboardingDateRules.value = [required('请选择入职日期')]
				}
				break
		}
	}

	// 关闭抽屉
	const onClose = () => {
		formRef.value?.resetFields()
		Object.keys(formData).forEach((key) => {
			if (key === 'offerEntity') {
				Object.keys(formData.offerEntity).forEach((offerKey) => {
					formData.offerEntity[offerKey] = undefined
				})
			} else {
				formData[key] = undefined
			}
		})

		// 重置展示数据和时间选择器
		Object.keys(displayData).forEach((key) => (displayData[key] = undefined))
		interviewTimeValue.value = null
		onboardingDateValue.value = null

		// 重置用户信息
		Object.keys(interviewerUser).forEach((key) => (interviewerUser[key] = undefined))
		Object.keys(coreInterviewerUser).forEach((key) => (coreInterviewerUser[key] = undefined))

		// 重置校验规则
		onboardingDateRules.value = []
		showSection.value = ''
		visible.value = false
		submitLoading.value = false
	}

	// 面试官回调
	const interviewerCallBack = (users) => {
		if (users?.length > 0) {
			const user = users[0]
			interviewerUser.id = user.id
			interviewerUser.name = user.name
			formData.interviewer = user.id
		}
	}

	// 核心面试官回调
	const coreInterviewerCallBack = (users) => {
		if (users?.length > 0) {
			const user = users[0]
			coreInterviewerUser.id = user.id
			coreInterviewerUser.name = user.name
			formData.coreInterviewer = user.id
		}
	}

	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				if (showSection.value === 'followup' && formData.sendOffer && offerFormRef.value) {
					return offerFormRef.value.validate().then(() => {
						submitInterviewData()
					})
				} else {
					submitInterviewData()
				}
			})
			.catch(() => {
				submitLoading.value = false
			})
	}

	const submitInterviewData = () => {
		submitLoading.value = true
		const submitFormData = { id: formData.id }
		switch (showSection.value) {
			case 'scheduling':
				submitFormData.type = 'scheduling'
				submitFormData.interviewTime = formData.interviewTime
				submitFormData.interviewMethod = formData.interviewMethod
				submitFormData.interviewer = formData.interviewer
				submitFormData.coreInterviewer = formData.coreInterviewer
				break
			case 'result':
				submitFormData.type = 'result'
				submitFormData.interviewResult = formData.interviewResult
				submitFormData.interviewFeedback = formData.interviewFeedback
				break
			case 'followup':
				submitFormData.type = 'followup'
				submitFormData.hiringResult = formData.hiringResult
				submitFormData.onboardingDate = formData.onboardingDate
				submitFormData.sendOffer = formData.sendOffer
				submitFormData.remark = formData.remark
				if (formData.sendOffer) {
					submitFormData.offerEntity = {
						...formData.offerEntity,
						candidateId: formData.id,
						candidateName: displayData.candidateName,
						positionCode: displayData.recommendedPositionCode,
						orgId: displayData.recommendedDepartmentId,
						orgName: displayData.recommendedDepartmentName,
						onboardingDate: formData.onboardingDate,
						branch: displayData.city,
						branchName: displayData.cityName
					}
				}
				break
		}
		recruitmentProfileApi
			.interview(submitFormData)
			.then(() => {
				message.success(formData.id ? '面试安排更新成功' : '面试安排保存成功')
				onClose()
				emit('successful')
			})
			.catch((error) => {
				message.error((formData.id ? '面试安排更新失败: ' : '面试安排保存失败: ') + (error.message || ''))
			})
			.finally(() => {
				submitLoading.value = false
			})
	}

	defineExpose({
		onOpen
	})
</script>
